<template>
  <div class="search-page">
    <van-nav-bar title="搜索" left-arrow @click-left="goBack">
      <template #title>
        <van-search
          v-model="searchKeyword"
          placeholder="搜索商品"
          @search="onSearch"
          @clear="onClear"
          autofocus
        />
      </template>
    </van-nav-bar>
    
    <!-- 搜索历史 -->
    <div v-if="!searchKeyword && searchHistory.length > 0" class="search-history">
      <div class="history-header">
        <span>搜索历史</span>
        <van-icon name="delete" @click="clearHistory" />
      </div>
      <div class="history-tags">
        <van-tag
          v-for="item in searchHistory"
          :key="item"
          @click="searchByHistory(item)"
          closeable
          @close="removeHistory(item)"
        >
          {{ item }}
        </van-tag>
      </div>
    </div>
    
    <!-- 热门搜索 -->
    <div v-if="!searchKeyword" class="hot-search">
      <div class="hot-header">热门搜索</div>
      <div class="hot-tags">
        <van-tag
          v-for="item in hotSearch"
          :key="item"
          type="primary"
          @click="searchByHistory(item)"
        >
          {{ item }}
        </van-tag>
      </div>
    </div>
    
    <!-- 搜索结果 -->
    <div v-if="searchKeyword" class="search-results">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadMore"
      >
        <div class="result-grid">
          <spu-preview
            v-for="spu in searchResults"
            :key="spu.id"
            :spu="spu"
            @click="goToDetail(spu.id)"
          />
        </div>
      </van-list>
      
      <!-- 空状态 -->
      <van-empty v-if="searchResults.length === 0 && !loading" description="暂无搜索结果" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getSpuList } from '@/api/home'
import SpuPreview from '@/components/spu-preview/index.vue'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const searchHistory = ref([])
const hotSearch = ref(['连衣裙', 'T恤', '牛仔裤', '运动鞋', '包包', '化妆品'])
const searchResults = ref([])
const loading = ref(false)
const finished = ref(false)
const page = ref(1)
const pageSize = 10

// 搜索
const onSearch = () => {
  if (!searchKeyword.value.trim()) {
    showToast('请输入搜索关键词')
    return
  }
  
  addToHistory(searchKeyword.value)
  resetResults()
  getSearchResults(true)
}

// 清空搜索
const onClear = () => {
  searchKeyword.value = ''
  searchResults.value = []
}

// 添加搜索历史
const addToHistory = (keyword) => {
  const history = searchHistory.value
  const index = history.indexOf(keyword)
  
  if (index > -1) {
    history.splice(index, 1)
  }
  
  history.unshift(keyword)
  
  if (history.length > 10) {
    history.pop()
  }
  
  searchHistory.value = history
  localStorage.setItem('searchHistory', JSON.stringify(history))
}

// 移除搜索历史
const removeHistory = (keyword) => {
  const index = searchHistory.value.indexOf(keyword)
  if (index > -1) {
    searchHistory.value.splice(index, 1)
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
  }
}

// 清空搜索历史
const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
}

// 通过历史记录搜索
const searchByHistory = (keyword) => {
  searchKeyword.value = keyword
  onSearch()
}

// 获取搜索结果
const getSearchResults = async (reset = false) => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    const params = {
      page: reset ? 1 : page.value,
      pageSize,
      keyword: searchKeyword.value
    }
    
    const data = await getSpuList(params)
    
    if (data && data.items) {
      if (reset) {
        searchResults.value = data.items
        page.value = 2
      } else {
        searchResults.value.push(...data.items)
        page.value++
      }
      
      if (data.items.length < pageSize) {
        finished.value = true
      }
    } else {
      finished.value = true
    }
  } catch (error) {
    console.error('搜索失败:', error)
    showToast('搜索失败')
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  getSearchResults()
}

// 重置结果
const resetResults = () => {
  searchResults.value = []
  page.value = 1
  finished.value = false
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 跳转到商品详情
const goToDetail = (spuId) => {
  router.push(`/detail/${spuId}`)
}

// 组件挂载时加载搜索历史
onMounted(() => {
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
})
</script>

<style lang="scss" scoped>
.search-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-history {
  background: #fff;
  margin: 10px;
  padding: 15px;
  border-radius: 8px;
  
  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    font-size: 14px;
    color: #333;
  }
  
  .history-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
}

.hot-search {
  background: #fff;
  margin: 10px;
  padding: 15px;
  border-radius: 8px;
  
  .hot-header {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
  }
  
  .hot-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
}

.search-results {
  .result-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    padding: 10px;
  }
}
</style> 